package com.scfire.weixin

import static groovyx.net.http.ContentType.URLENC
import groovyx.net.http.RESTClient
import javax.servlet.http.HttpSession
import net.sf.json.JSONArray
import net.sf.json.JSONObject

import org.dom4j.*
import org.dom4j.io.*

import com.scfire.project.Donate
import com.scfire.security.Authority
import com.scfire.security.Member
import com.scfire.security.MemberAuthority
import com.scfire.util.MailUtil


/** 
 * Copyright 2015 Shudao Info Tech Co. Ltd.  All rights reserved.
 * @author lhzeng
 * @email zenglh@haoshudao.com
 * @date 2015年6月7日 下午11:56:37 
 * @version V1.0
 */

class WeiXinService {
	
	def userLocationService
	/*
	 * -------------------------------
	 * 微信支付用到的方法  开始
	 * 其中用到了  引入js模块所用的方法
	 */
	/**
	 * 微信发起支付请求
	 */
	def Map getOrder(String body , String detail , int total_fee , String openid , String attach){
		Map<String , String> map = new HashMap<String , String>()
		
		long timestamp = System.currentTimeMillis()/1000
		String nonce_str = WeiXinUtil.getRandomString(32)
		String out_trade_no = mch_billno()
		String spbill_create_ip = WeiXinConstants.spbill_create_ip
		String notify_url = WeiXinConstants.notify_url
		String trade_type = "JSAPI"
		
		SortedMap<Object,Object> param = new TreeMap<Object,Object>()
		param.put("appid", WeiXinConstants.appid)
		param.put("mch_id", WeiXinConstants.mch_id)
		param.put("nonce_str", nonce_str)
		param.put("body", body)
		param.put("detail", detail)
		param.put("out_trade_no", out_trade_no)
		param.put("total_fee", total_fee)
		param.put("spbill_create_ip", spbill_create_ip)
		param.put("notify_url", notify_url)
		param.put("trade_type", trade_type)
		param.put("openid", openid)
		param.put("timeStamp", timestamp)
		param.put("attach", attach)
		String sign = MD5Sign.createSign("UTF-8",param , WeiXinConstants.mch_key)
		
		String value = "<xml>\r\n"+
		"<appid>"+WeiXinConstants.appid+"</appid>"+
		"<mch_id>"+WeiXinConstants.mch_id+"</mch_id>\r\n"+
		"<nonce_str>"+nonce_str+"</nonce_str>\r\n"+
		"<body>"+body+"</body>\r\n"+
		"<detail>"+detail+"</detail>\r\n"+
		"<out_trade_no>"+out_trade_no+"</out_trade_no>\r\n"+
		"<total_fee>"+total_fee+"</total_fee>\r\n"+
		"<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>\r\n"+
		"<notify_url>"+notify_url+"</notify_url>\r\n"+
		"<trade_type>"+trade_type+"</trade_type>\r\n"+
		"<openid>"+openid+"</openid>\r\n"+
		"<timeStamp>"+timestamp+"</timeStamp>\r\n"+
		"<attach>"+attach+"</attach>\r\n"+
		"<sign>"+sign+"</sign>\r\n"+
		"</xml>"
		
		String billnoInfo = WeiXinUtil.postXML(WeiXinConstants.billno_url , value)
		String prepay_id = WeiXinUtil.getValue(billnoInfo , "prepay_id")
		
		SortedMap<Object,Object> param2 = new TreeMap<Object,Object>()
		param2.put("timeStamp", timestamp)
		param2.put("nonceStr", nonce_str)
		param2.put("package", 'prepay_id='+prepay_id)
		param2.put("signType", "MD5")
		param2.put("appId", WeiXinConstants.appid)
		
		String paySign = MD5Sign.createSign("UTF-8",param2 , WeiXinConstants.mch_key)
		
		map.put("prepay_id", prepay_id)
		map.put("paySign", paySign)
		map.put("timeStamp", timestamp)
		map.put("nonce_str", nonce_str)
		
		return map
	}
	/*
	 * 微信支付用到的方法 结束
	 * -------------------------------
	 */
	
	/**
	 * 用户操作事件，微信回调方法
	 * @param map
	 * @param MsgType
	 * @param Event
	 * @param openid
	 * @param content
	 * @param createTime
	 */
	public String event(Map<String, String> map,String MsgType , String Event , String openid , String content , String createTime , String eventKey){
		println MsgType + "-----" + Event + "-----" + openid
		
		String info = ""
		//用户关注
		if(MsgType == "event" && Event == "subscribe"){
//			info = sendNobelArticleMessage(openid)
//			return info
			String msg = "感谢您的关注与支持。\r\n"+
			"我们是火堆团队，旨在打造中国首家教育垂直领域的公益众筹平台--帮助普通的教育实践者实现教育理想，为公众提供值得信赖的公益平台，让教育成为每个人的教育。\r\n"+
			"1.点击屏幕左下角“浏览项目”支持触动你的故事。\r\n"+
			"2.问题咨询、项目合作您可直接在微信号回复您的“需求+联系方式”，我们会在工作日期间尽快答复。\r\n"
			AutoReply  auto= AutoReply.findById(1)
			if(auto) msg = auto.content;
			this.sendMsg(openid, msg)
			
		}
		//用户取消关注
		if(MsgType == "event" && Event == "unsubscribe"){
//			return document
		}
		//点击事件
		if(MsgType == "event" && Event == "CLICK"){
			//火堆说  咨询的key   与菜单栏中的key一一对应
			if(eventKey == 'consult'){
				String msg = "感谢您对火堆的关注和支持。如果你想要加入我们，您可以：\r\n"+
				"1、成为火堆项目发起人：请回复关键字“发起项目”\r\n"+
				"2、成为火堆合作伙伴：请点击“成为合伙人”，或请联系火堆·社群经理：021-31767525。\r\n"+
				"3、成为火堆项目捐赠人：进入“爱心捐助”选择项目，选择触动你的那个公益项目，支持ta的公益梦想。\r\n"
				this.sendMsg(openid, msg)
			}
			if(eventKey == 'diary'){
				info = sendArticleMessage(openid)
			}
		}
		//用户向公众号发送文本消息
		if(MsgType == "text"){
			if(content.contains("发起项目")){
				info = applyTemplateArticleMessage(openid)
			}
			//用户向公众号发送十二星座   ！
			if(content.contains("白羊")){
				info = replyConstellation(openid, "68", "白羊座为爱而战筹建梦想中心")
			}
			else if(content.contains("双子")){
				info = replyConstellation(openid, "69", "双子座为爱而战筹建梦想中心")
			}
			else if(content.contains("双鱼")){
				info = replyConstellation(openid, "70", "双鱼座为爱而战筹建梦想中心")
			}
			else if(content.contains("狮子")){
				info = replyConstellation(openid, "71", "狮子座为爱而战筹建梦想中心")
			}
			else if(content.contains("巨蟹")){
				info = replyConstellation(openid, "72", "巨蟹座为爱而战筹建梦想中心")
			}
			else if(content.contains("金牛")){
				info = replyConstellation(openid, "73", "金牛座为爱而战筹建梦想中心")
			}
			else if(content.contains("处女")){
				info = replyConstellation(openid, "74", "处女座为爱而战筹建梦想中心")
			}
			else if(content.contains("水瓶")){
				info = replyConstellation(openid, "75", "水瓶座为爱而战筹建梦想中心")
			}
			else if(content.contains("摩羯")){
				info = replyConstellation(openid, "76", "摩羯座为爱而战筹建梦想中心")
			}
			else if(content.contains("射手")){
				info = replyConstellation(openid, "77", "射手座为爱而战筹建梦想中心")
			}
			else if(content.contains("天秤")){
				info = replyConstellation(openid, "78", "天秤座为爱而战筹建梦想中心")
			}
			else if(content.contains("天蝎")){
				info = replyConstellation(openid, "79", "天蝎座为爱而战筹建梦想中心")
			}
		}
		
		return info
	}
	
	/*
	 * ------------------------------------
	 * oauth认证所用到的方法开始
	 * 
	 */
	/**
	 * 微信oauth认证 , 获取access_token
	 * 这个token 和  getToken()方法中 token不同
	 * 该token只为oauth认证服务
	 * @return
	 */
	def JSONObject oauth_accessToken(String code){
		RESTClient rest = new RESTClient(WeiXinConstants.oauth_token_url+"?appid="+WeiXinConstants.appid+"&secret="+WeiXinConstants.appsecurity+"&code="+code+"&grant_type=authorization_code")
		def resp = rest.post(body:[:],requestContentType : "application/json")
		return JSONObject.fromObject(resp.data.text)
	}
	/**
	 * 微信oauth认证， 获取授权用户信息
	 * @param code
	 * @return
	 */
	def JSONObject getUserInfo(String code){
		JSONObject accessToken = this.oauth_accessToken(code)
		RESTClient rest = new RESTClient(WeiXinConstants.oauth_user_info_url+"?access_token="+accessToken.access_token+"&openid="+accessToken.openid+"&lang=zh_CN")
		def resp = rest.post(body:[:],requestContentType : "application/json")
		return JSONObject.fromObject(resp.data.text)
	}
	
	/*
	 * oauth认证所用到的方法结束
	 * ------------------------------------
	 *
	 */
	/**
	 * 微信公众号 access_token获取
	 * 要与oauth token区分
	 */
	public synchronized String getToken(){
		try{
			if(WeiXinConstants.access_token == null){
				this.getAccessToken()
			}else if((System.currentTimeMillis() - WeiXinConstants.access_time) >= WeiXinConstants.expires_in){
				this.getAccessToken()
			}else{
				return WeiXinConstants.access_token
			}
		}catch(Exception e){
			e.printStackTrace()
			return null
		}
		return WeiXinConstants.access_token
	}
	/*
	 * ----------------------------------
	 * 微信页面引入js 所用到的方法开始
	 */
	/**
	 * jsapi_ticket所需的签名验证
	 * 页面引入微信js  config中所用到的参数， 所做封装
	 */
	public Map jsapiTicketSign(def uri){
		def noncestr = WeiXinUtil.getRandomString(32)
		def jsapi_ticket = this.getJsapiTicketCache()
		long timestamp = System.currentTimeMillis()/1000
		def url = uri
		
		SortedMap<Object,Object> sortMap = new TreeMap<Object,Object>()
		sortMap.put("noncestr", noncestr)
		sortMap.put("jsapi_ticket", jsapi_ticket)
		sortMap.put("timestamp", timestamp)
		sortMap.put("url", url)
		
		def sign = Sha1Util.signature(sortMap)
		Map<String , String> res = new HashMap<String , String>()
		res.put("noncestr", noncestr)
		res.put("jsapi_ticket", jsapi_ticket)
		res.put("timestamp", timestamp)
		res.put("url", url)
		res.put("sign" , sign)
		
		return res
	}
	/**
	 * 微信公众号sjapi_ticket   服务器缓存
	 * 获取页面加载js时，签名所用的jsapi_ticket获取
	 */
	public synchronized String getJsapiTicketCache(){
		try{
			if(WeiXinConstants.sjapi_ticket == null){
				this.getJsapiTicket()
			}else if((System.currentTimeMillis() - WeiXinConstants.sjapi_ticket_time) >= WeiXinConstants.expires_in){
				this.getJsapiTicket()
			}else{
				return WeiXinConstants.sjapi_ticket
			}
		}catch(Exception e){
			e.printStackTrace()
			return null
		}
		return WeiXinConstants.sjapi_ticket
	}
	/**
	 * 获取页面js中所需要的  sjapi_ticket   不支持其他地方调用 ， 获取 sjapi_ticket 请用 getJsapiTicketCache()方法
	 */
	private synchronized void getJsapiTicket(){
		JSONObject sjapiTicket = null
		RESTClient rest = new RESTClient(WeiXinConstants.js_sjapi_ticket_url+this.getToken())
		try{
			def resp = rest.post(body:[:],requestContentType : URLENC)
			sjapiTicket = JSONObject.fromObject(resp.responseData)
			println "获取sjapiTicket内容："+sjapiTicket
			if(sjapiTicket.containsKey("ticket")){
				WeiXinConstants.sjapi_ticket = sjapiTicket.ticket
				WeiXinConstants.sjapi_ticket_time = System.currentTimeMillis()
			}
		}catch(Exception e){
				e.printStackTrace()
		}
	}
	/*
	 *微信页面引入js 所用到的方法 结束
	 * ----------------------------------
	 */
	
	
	/*
	 * ----------------------------------
	 * 与微信交互常用的方法 开始
	 */
	/**
	 * 账号密码获取access_token,实现单例，
	 * 获取oauth token请使用oauth_accessToken()方法
	 */
	private synchronized void getAccessToken() {
		JSONObject accessToken = null
		RESTClient rest = new RESTClient(WeiXinConstants.access_token_url)
		try{
			def resp = rest.post(body:[appid: WeiXinConstants.appid , secret : WeiXinConstants.appsecurity],requestContentType : URLENC)
			accessToken = JSONObject.fromObject(resp.responseData)
			if(accessToken.containsKey("access_token")){
				WeiXinConstants.access_token = accessToken.access_token
				WeiXinConstants.access_time = System.currentTimeMillis()
			}
		}catch(Exception e){
			e.printStackTrace()
		}
	}
	/**
	 * 生成订单号
	 * @return
	 */
	def synchronized static mch_billno(){
		StringBuffer str = new StringBuffer()
		Calendar date = Calendar.getInstance()
		int year = date.get(Calendar.YEAR)
		int month = date.get(Calendar.MONTH)+1
		int DATE = date.get(Calendar.DATE)
		//时间变更，制空Map数组
		if(WeiXinConstants.mch_billno_date !=DATE){
			WeiXinConstants.mch_billno_date = DATE
			WeiXinConstants.mch_billno_map.clear()
		}
		str.append(WeiXinConstants.mch_id)
		str.append(year)
		if(month<=9){
			str.append(0)
		}
		str.append(month)
		str.append(DATE)
		
		String randomNum = WeiXinUtil.tenRandomNum()
		while(WeiXinConstants.mch_billno_map.containsKey(randomNum)){
			randomNum = WeiXinUtil.tenRandomNum()
		}
		WeiXinConstants.mch_billno_map.put(randomNum , randomNum)
		
		str.append(randomNum)
		return str.toString()
	}
	/**
	 * 解析XML为HashMap
	 */
	public Map parseXML(InputStream stream){
		Map<String, String> map = new HashMap<String, String>()
		
		SAXReader reader = new SAXReader()
		Document document = reader.read(stream)
		Element root = document.getRootElement()
		
		List<Element> elementList = root.elements()
		for (Element e : elementList){
			map.put(e.getName(), e.getText())
		}
	   stream.close()
	   stream = null
	   return map
	}
	/**
	 * 保存或更新用户信息
	 */
	public Member saveMember(JSONObject member , String type,String otherUnionId){
		Member user
		if(type == "微信mobile端"){
			def openid = member?.openid
			user = Member.findByOpenid(openid)
			if(!user){
				def otherUser
				if(otherUnionId!=null&&otherUnionId!=""){
					otherUser = Member.findByOtherUnionid(otherUnionId)
				}
				if(otherUser!=null && !(otherUser?.openid)){
					otherUser.openid = member.openid
					otherUser.nickname = member.nickname
					otherUser.province = member.province
					otherUser.city = member.city
					otherUser.country = member.country
					otherUser.headimgurl = member.headimgurl
					otherUser.unionid = member.unionid
					if(member?.sex == 1){
						otherUser.sex = "男"
					}
					if(member?.sex == 2){
						otherUser.sex = "女"
					}
					if(member?.sex == 0){
						otherUser.sex = "未知"
					}
					otherUser.save(flush : true)
					user=otherUser;
				}else{
					user = new Member()
					user.username = UUID.randomUUID().toString().replaceAll("-", "").toString()
					user.password = "csstsari"
					user.enabled = true
					user.accountExpired = false
					user.accountLocked = false
					user.passwordExpired = false
					user.openid = member.openid
					user.nickname = member.nickname
					user.province = member.province
					user.city = member.city
					user.country = member.country
					user.headimgurl = member.headimgurl
					user.unionid = member.unionid
					
					if(member?.sex == 1){
						user.sex = "男"
					}
					if(member?.sex == 2){
						user.sex = "女"
					}
					if(member?.sex == 0){
						user.sex = "未知"
					}
					user.save(flush : true)
					//创建权限
					Authority authority = Authority.findByAuthority("ROLE_USER")
					def memberAuthority = MemberAuthority.get(user?.id,authority.id)
					if(!memberAuthority){
						MemberAuthority.create(user , authority , true)
					}
			}
				

				
			}else{
			
			if(otherUnionId==user?.otherUnionid){
			}else{
			println otherUnionId
			println user?.otherUnionid
				def otherUser = Member.findByOtherUnionid(otherUnionId)
			
				if(otherUser?.openid){
					//有openid,证明已经关联成功
				}else{
				//其他渠道进入火堆后绑定火堆用户，并将捐赠转移至火堆平台。
					def donates = Donate.findAllByOpenid(otherUnionId);
					for(Donate d: donates){
					  d.member = user.id
					  println d.id
					  d.save(flush:true);
					}
					otherUser.enabled= false;
					otherUser.save(flush:true);
					user?.otherUnionid=otherUnionId
					user.save(flush:true);
				}
			   
			}
				//不做微信同步更新操作
				/*user.openid = member.openid
				user.nickname = member.nickname
				user.province = member.province
				user.city = member.city
				user.country = member.country
				user.headimgurl = member.headimgurl
				user.unionid = member.unionid
	
				if(member?.sex == 1){
					user.sex = "男"
				}
				if(member?.sex == 2){
					user.sex = "女"
				}
				if(member?.sex == 0){
					user.sex = "未知"
				}
				user.save(flush : true)*/
			}
		}else{
			return null
		}
		
		println user.nickname+"--------"
		println user.openid+"++++++++++"
		return user
//		Member user
//		if(type == "微信mobile端" || type == "微信PC端"){
//			
//			def unionid = member?.unionid
//			user = Member.findByUnionid(unionid)
//			if(!user){
//				user = new Member()
//				user.username = UUID.randomUUID().toString().replaceAll("-", "").toString()
//				user.password = "csstsari"
//				user.enabled = true
//				user.accountExpired = false
//				user.accountLocked = false
//				user.passwordExpired = false
//				if(type == "微信mobile端"){
//					user.mobileOpenid = member.openid
//				}
//				if(type == "微信PC端"){
//					user.pcOpenid = member.openid
//				}
//				user.nickname = member.nickname
//				user.province = member.province
//				user.city = member.city
//				user.country = member.country
//				user.headimgurl = member.headimgurl
//				user.unionid = member.unionid
//				
//				if(member?.sex.equals("1")){
//					user.sex = "男"
//				}
//				if(member?.sex.equals("2")){
//					user.sex = "女"
//				}
//				if(member?.sex.equals("0")){
//					user.sex = "未知"
//				}
//				user.save(flush : true)
//				
//				//创建权限
//				Authority authority = Authority.findByAuthority("ROLE_USER")
//				def memberAuthority = MemberAuthority.get(user?.id,authority.id)
//				if(!memberAuthority){
//					MemberAuthority.create(user , authority , true)
//				}
//				
//			}else{
//				if(type == "微信mobile端"){
//					user.mobileOpenid = member.openid
//				}
//				if(type == "微信PC端"){
//					user.pcOpenid = member.openid
//				}
//				user.nickname = member.nickname
//				user.province = member.province
//				user.city = member.city
//				user.country = member.country
//				user.headimgurl = member.headimgurl
//				user.unionid = member.unionid
//				
//				if(member?.sex.equals("1")){
//					user.sex = "男"
//				}
//				if(member?.sex.equals("2")){
//					user.sex = "女"
//				}
//				if(member?.sex.equals("0")){
//					user.sex = "未知"
//				}
//				user.save(flush : true)
//			}
//		}
//		return user
	}
	/**
	 * 微信回调，验证签名
	 */
	public boolean checkSignature(String signature, String timestamp, String nonce){
		return SignUtil.checkSignature(signature, timestamp, nonce)
	}
	/**
	 * 微信增加菜单
	 */
	public JSONObject createMenu(){
		
		RESTClient rest = new RESTClient(WeiXinConstants.weixin_menu_url+"?access_token="+this.getToken())
		try{

			List<MainMenu> mainMenus = MainMenu.list("sort":"position")
			String value = "";
			if(mainMenus.size()>0){
				JSONObject result = new JSONObject();
				JSONArray main_buttons = new JSONArray();
				for(int i=0;i<mainMenus.size();i++){
					MainMenu mainMenu = mainMenus.get(i)
					JSONObject mainbtn = new JSONObject();
					mainbtn.put("name",mainMenu.name);

					def subs = mainMenu.subMenus;
					if(subs.size()==0){
						mainbtn.put("type", mainMenu.type);
						if(mainMenu.type=="view")
							mainbtn.put("url",mainMenu.key);
						else mainbtn.put("key", mainMenu.key);
					}
					else{

						JSONArray sub_buttons = new JSONArray();
						int j=0;
						Iterator it= subs.iterator();
						while(it.hasNext()) {
							SubMenu sub = it.next();
							JSONObject subbtn = new JSONObject();
							subbtn.put("name",sub.name);
							subbtn.put("type", sub.type);
							if(sub.type=="view")
								subbtn.put("url",sub.key);
							else subbtn.put("key", sub.key);
							sub_buttons.add(j, subbtn);
							j++;
						}
						mainbtn.put("sub_button", sub_buttons);
						
					}
					main_buttons.add(i, mainbtn)
				}
				result.put("button", main_buttons)
				value = result.toString()
			}
			
//	   String value = ''+
//		'{\r\n'+
//			'"button":[\r\n'+
//
//			  '{\r\n'+
//				  '"type":"view",\r\n'+
//				  '"name":"浏览项目",\r\n'+
//				  '"url":"http://www.huodui.org/scfire/index/index"\r\n'+
//			  '},\r\n'+
//			  
//			  '{\r\n'+
//			  '"name":"火堆说",\r\n'+
//			  '"sub_button":[\r\n'+
//				  	'{\r\n'+
//					  '"type":"view",\r\n'+
//					  '"name":"关于火堆",\r\n'+
//					  '"url":"http://www.rabbitpre.com/apps/55aef31530fdb8c71b3a197f"\r\n'+
//					 '},\r\n'+
//			  
//					 '{\r\n'+
//					 '"type":"view",\r\n'+
//					 '"name":"成为合伙人",\r\n'+
//					 '"url":"https://ssl.gongyi.qq.com/m/weixin/detail.htm?showwxpaytitle=1#p%3Ddetail%26id%3D2300"\r\n'+
//					 '},\r\n'+
//					 
//					 '{\r\n'+
//					 '"type":"view",\r\n'+
//					 '"name":"我要提问",\r\n'+
//					 '"url":"http://form.mikecrm.com/f.php?t=OfJiop"\r\n'+
//					 '},\r\n'+
//					 
//					 '{\r\n'+
//					 '"type":"click",\r\n'+
//					 '"name":"火堆咨询",\r\n'+
//					 '"key":"consult"\r\n'+
//					 '},'+
//					 
//					 '{\r\n'+
//					 '"type":"click",\r\n'+
//					 '"name":"创业日记",\r\n'+
//					 '"key":"diary"\r\n'+
//					 '}'+
//			
//				']\r\n'+
//			 
//			 '},\r\n'+
//			 
//			 '{\r\n'+
//			  '"type":"view",\r\n'+
//			  '"name":"个人中心",\r\n'+
//			  '"url":"http://www.huodui.org/scfire/user/userCenter"\r\n'+
//			  '}\r\n'+
//
//		'}\r\n'
//	   
			def resp = rest.post(body: value,requestContentType : "text/plain")
			JSONObject user = JSONObject.fromObject(resp.responseData)
			println user.toString()
			return user
		}catch(Exception e){
			e.printStackTrace()
		}
		
	}
	
	/**
	 * 微信自动回复内容设置
	 */
	public JSONObject createAutoReplyContent(){
		
		RESTClient rest = new RESTClient(WeiXinConstants.weixin_auto_reply+"?access_token="+this.getToken())
		
		try{
			
	    String value = ''+
		'{\r\n'+
		
			'"is_add_friend_reply_open": 1,\r\n'+			
			'"is_autoreply_open": 1,\r\n'+
						
			'"add_friend_autoreply_info": {\r\n'+
				'"type": "text",\r\n'+				
				'"content": "感谢您的关注与支持."\r\n'+
				'"我们是火堆团队，旨在打造中国首个教育垂直领域公益众筹平台--帮助教育实践者实现教育理想，为公众提供值得信赖的公益众筹平台。"\r\n'+
				'"1.点击屏幕左下角。\"浏览项目\"支持教育项目。"\r\n'+
				'"2.问题咨询、项目合作请直在本微信公众号中回复您的需求+联系方式，我们会在工作日期间尽快答复。"\r\n'+
				'\r\n'+
				'"诚邀热心公益、心系教育的你与我们同行。"\r\n'+
			'}\r\n'+

		'}\r\n'
			
		
			def resp = rest.post(body: value,requestContentType : "text/plain")
			JSONObject user = JSONObject.fromObject(resp.responseData)
			return user
		}catch(Exception e){
			e.printStackTrace()
		}
		
	}
	
	/**
	 * 向特定用户发送文本消息
	 *
	 */
	def JSONObject sendMsg(String openid , String text){
		String json = "{\"touser\":\""+openid+"\",\"msgtype\":\"text\",\"text\":{\"content\":\""+text+"\"}}"
		RESTClient rest = new RESTClient(WeiXinConstants.weixin_send_message+"?access_token="+this.getToken())
		def resp = rest.post(body: json,requestContentType : "text/plain")
		JSONObject respon = JSONObject.fromObject(resp.responseData)
		return respon
	}
	
	/**
	 *支付成功，模板接口
	 */
	def boolean templet(String templetId , String openid , String url , String projectName , String price , String nickname){
		
		String json = ''+
		'{'+
			'"touser":"'+openid+'",'+
			'"template_id":"'+templetId+'",'+
			'"url":"'+url+'",'+
			'"topcolor":"#FF0000",'+
			'"data":{'+
					'"first": {'+
						'"value":"亲爱的'+nickname+'，你已成功捐赠'+price+'元。",'+
						'"color":"#173177"'+
					'},'+
					'"DonateNum":{'+
						'"value":"'+projectName+'",'+
						'"color":"#173177"'+
					'},'+
					'"DonateSum": {'+
						'"value":"'+price+'元",'+
						'"color":"#173177"'+
					'},'+
					'"remark":{'+
						'"value":"我们会定期公布善款执行明细，敬请关注。点击详情查看专属爱心捐赠证书。",'+
						'"color":"#173177"'+
					'}'+
			'}'+
		'}'
		RESTClient rest = new RESTClient(WeiXinConstants.weixin_template_message+"?access_token="+this.getToken())
		def resp = rest.post(body: json,requestContentType : "text/plain")
		JSONObject respon = JSONObject.fromObject(resp.responseData)
		println respon
		if(respon?.errmsg == "ok"){
			
			return true
		}
		return false
		
	} 
	
	/**
	 * 群发模板接口
	 */
	def void sendMassTemplateStatus(String template_id , Map openids , String first , String keyword1  ,String keyword2 , String keyword3 , String remark , String url){
		Thread.start {
			if(openids){
				for (String key : openids.keySet()) {
					template_status(WeiXinConstants.service_id, key, first, keyword1, keyword2, keyword3, remark , url)
					Thread.sleep(100)
				}
			}
		}
	}
	
	/**
	 * 群发模板接口
	 */
	def void sendMassTemplateStatus2(String template_id , Map openids , String first , String keyword1  ,String keyword2 , String keyword3 , String remark , String url){
		Thread.start {
			if(openids){
				for (String key : openids.keySet()) {
					String s=openids.get(key)+first
					template_status(WeiXinConstants.service_id, key, s, keyword1, keyword2, keyword3, remark , url)
					Thread.sleep(100)
					println s+"----------"+key
				}
			}
		}
	}
	/**
	 * 模板接口
	 * 项目审核状态  筹款状态 以及实名状态 发送模板消息
	 */
	def boolean template_status(String template_id , String openid , String first , String keyword1  ,String keyword2 , String keyword3 , String remark , String url){
		String json = ''+
		'{'+
			'"touser":"'+openid+'",'+
			'"template_id":"'+template_id+'",'+
			'"url":"'+url+'",'+
			'"topcolor":"#FF0000",'+
			'"data":{'+
					'"first": {'+
						'"value":"'+first+'",'+
						'"color":"#173177"'+
					'},'+
					'"keyword1":{'+
						'"value":"'+keyword1+'",'+
						'"color":"#173177"'+
					'},'+
					'"keyword2": {'+
						'"value":"'+keyword2+'",'+
						'"color":"#173177"'+
					'},'+
					'"keyword3":{'+
						'"value":"'+keyword3+'",'+
						'"color":"#173177"'+
					'},'+
					'"remark":{'+
					'"value":"'+remark+'",'+
					'"color":"#173177"'+
				'}'+
			'}'+
		'}'
		RESTClient rest = new RESTClient(WeiXinConstants.weixin_template_message+"?access_token="+this.getToken())
		def resp = rest.post(body: json,requestContentType : "text/plain")
		JSONObject respon = JSONObject.fromObject(resp.responseData)
		println respon
		if(respon?.errmsg == "ok"){
			return true
		}
		return false
		
		
	}
	
	/**
	 * 获取素材
	 */
	def JSONObject getMaterial(int offset , int count){
		String json = ""+
		"{"+
			"\"type\":\"news\","+
			"\"offset\":$offset,"+
			"\"count\":$count"+
		"}"
		println json
		RESTClient rest = new RESTClient(WeiXinConstants.weixin_material+"?access_token="+this.getToken())
		def resp = rest.post(body: json,requestContentType : "text/plain")
		JSONObject respon = JSONObject.fromObject(resp.responseData.str)
		return respon
	}
	/**
	 * 发送创业日记消息
	 */
	def String sendArticleMessage(def openid){
		String value = ""+
		"<xml>"+
		"<ToUserName>"+openid+"</ToUserName>"+
		"<FromUserName>"+WeiXinConstants.weixinNumber+"</FromUserName>"+
		"<CreateTime>"+((Long)System.currentTimeMillis()/1000).intValue()+"</CreateTime>"+
		"<MsgType>news</MsgType>"+
		"<ArticleCount>3</ArticleCount>"+
		"<Articles>"+
		"<item>"+
		"<Title>创业日记 | 那些为火堆的日日夜夜</Title>"+
		"<Description></Description>"+
		"<PicUrl>https://mmbiz.qlogo.cn/mmbiz/0WFYlKicUOYkBXXiaB5BZjLrbJu1XIgP808hgyrVBlxM9cuAYPLHoE8zhO5iadbHC5E6ZKfTKbw3XuK8icianFicB9kQ/0?wx_fmt=jpeg</PicUrl>"+
		"<Url>http://mp.weixin.qq.com/s?__biz=MzAxNjM5NzExOQ==&amp;mid=209531987&amp;idx=1&amp;sn=9910d5961a4e7550cf6ee8d4ed7e8913#rd</Url>"+
		"</item>"+
		"<item>"+
		"<Title>创业日记 | 从0号反应堆讲起</Title>"+
		"<Description></Description>"+
		"<PicUrl>https://mmbiz.qlogo.cn/mmbiz/0WFYlKicUOYkBXXiaB5BZjLrbJu1XIgP80aEDuejwrZRTp42u24T72HYddibpa9TglkEZXbvZgj1lbYwJkF9ibxchw/0?wx_fmt=jpeg</PicUrl>"+
		"<Url>http://mp.weixin.qq.com/s?__biz=MzAxNjM5NzExOQ==&amp;mid=209531987&amp;idx=2&amp;sn=1f74eaa7683b0c82321fdae5c04fde24#rd</Url>"+
		"</item>"+
		"<item>"+
		"<Title>创业日记 | 天使，助燃火堆！</Title>"+
		"<Description></Description>"+
		"<PicUrl>https://mmbiz.qlogo.cn/mmbiz/0WFYlKicUOYkBXXiaB5BZjLrbJu1XIgP80P2CzNgibQfWHPyzDodMtBoBD240icfMIBqmEsx6DmxVZ74CABw1FlzXw/0?wx_fmt=jpeg</PicUrl>"+
		"<Url>http://mp.weixin.qq.com/s?__biz=MzAxNjM5NzExOQ==&amp;mid=209531987&amp;idx=3&amp;sn=d05432cdf0367f214f26173e5c580a06#rd</Url>"+
		"</item>"+
		"</Articles>"+
		"</xml>"
		return value
	}
	/**
	 * 发送诺贝尔教师奖获得者
	 */
	def sendNobelArticleMessage(def openid){
		String value = ""+
		"<xml>"+
		"<ToUserName>"+openid+"</ToUserName>"+
		"<FromUserName>"+WeiXinConstants.weixinNumber+"</FromUserName>"+
		"<CreateTime>"+((Long)System.currentTimeMillis()/1000).intValue()+"</CreateTime>"+
		"<MsgType>news</MsgType>"+
		"<ArticleCount>1</ArticleCount>"+
		"<Articles>"+
		"<item>"+
		"<Title>“诺贝尔教师奖”获得者</Title>"+
		"<Description></Description>"+
		"<PicUrl>https://mmbiz.qlogo.cn/mmbiz/0WFYlKicUOYkOpV8fZH9mbIvUuE1hGdquwuuNnsFGRXeNfpkfA6AVCQQdkRnFo1TbFzibwCwGevwNSuqIUo0Cc2g/0?wx_fmt=jpeg</PicUrl>"+
		"<Url>http://mp.weixin.qq.com/s?__biz=MzAxNjM5NzExOQ==&amp;mid=209752083&amp;idx=1&amp;sn=cf8d753b99582a5b079d57c0c1b3080f#rd</Url>"+
		"</item>"+
		"</Articles>"+
		"</xml>"
		return value
	}
	/**
	 * 发送火堆项目发起流程素材消息
	 */
	def applyTemplateArticleMessage(def openid){
		String value = ""+
		"<xml>"+
		"<ToUserName>"+openid+"</ToUserName>"+
		"<FromUserName>"+WeiXinConstants.weixinNumber+"</FromUserName>"+
		"<CreateTime>"+((Long)System.currentTimeMillis()/1000).intValue()+"</CreateTime>"+
		"<MsgType>news</MsgType>"+
		"<ArticleCount>2</ArticleCount>"+
		"<Articles>"+
		"<item>"+
		"<Title>火堆项目发起流程</Title>"+
		"<Description></Description>"+
		"<PicUrl>https://mmbiz.qlogo.cn/mmbiz/0WFYlKicUOYkAuQMdvy7bF7wyBkmVes0VuELugAB8iayRSiauHIUUudpVfbF07lSxlzFEN1x5phaOFrGr7bAr2VOQ/0?wx_fmt=jpeg</PicUrl>"+
		"<Url>http://mp.weixin.qq.com/s?__biz=MzAxNjM5NzExOQ==&amp;mid=210007781&amp;idx=1&amp;sn=696c8e46d41addee928b5e65763b4b85#rd</Url>"+
		"</item>"+
		"<item>"+
		"<Title>项目申请模板</Title>"+
		"<Description></Description>"+
		"<PicUrl>https://mmbiz.qlogo.cn/mmbiz/0WFYlKicUOYkAuQMdvy7bF7wyBkmVes0VStHbsGZ6gJ2b8OMb8Pdg7R8qFU7N223wLVOfPYyn3wv7qbjm2V8R3g/0?wx_fmt=jpeg</PicUrl>"+
		"<Url>http://mp.weixin.qq.com/s?__biz=MzAxNjM5NzExOQ==&amp;mid=210007781&amp;idx=2&amp;sn=bc365c53669c89c32c4ec2ca0467c6d3#rd</Url>"+
		"</item>"+
		"</Articles>"+
		"</xml>"
		return value
	}
	

	
	/**
	 * 12星座的消息推送
	 */
	def replyConstellation(def openid, String projectid, String title){
		String value = ""+
		"<xml>"+
		"<ToUserName>"+openid+"</ToUserName>"+
		"<FromUserName>"+WeiXinConstants.weixinNumber+"</FromUserName>"+
		"<CreateTime>"+((Long)System.currentTimeMillis()/1000).intValue()+"</CreateTime>"+
		"<MsgType>news</MsgType>"+
		"<ArticleCount>1</ArticleCount>"+
		"<Articles>"+
		"<item>"+
		"<Title>"+title+"</Title>"+
		"<Description></Description>"+
		"<Url>http://www.huodui.org/scfire/project/projectDetail?projectid="+projectid+"</Url>"+
		"</item>"+
		"</Articles>"+
		"</xml>"
		return value
	}
	/*
	 * 与微信交互常用的方法 结束
	 * ----------------------------------
	 */
	
	
	
	
	
	/*
	 * 微信pc端登陆授权方法 开始
	 * ------------------------------------
	 */
	/**
	 * pc登陆授权第二部
	 * 通过code获取access_token
	 * @param code
	 * @return
	 */
	private JSONObject get_pc_accesstoken(String code){
		RESTClient rest = new RESTClient(WeiXinConstants.oauth_token_url+"?appid="+WeiXinConstants.appid_pc+"&secret="+WeiXinConstants.appsecurity_pc+"&code="+code+"&grant_type=authorization_code")
		def resp = rest.post(body:[:],requestContentType : "application/json")
		JSONObject obj = JSONObject.fromObject(resp.data.text)
		return obj
	}
	/**
	 * 获取用户信息
	 * @param code
	 * @return
	 */
	def JSONObject get_pc_userinfo(String code){
		JSONObject access_token = get_pc_accesstoken(code)
		RESTClient rest = new RESTClient(WeiXinConstants.oauth_user_info_url+"?access_token="+access_token.access_token+"&openid="+access_token.openid)
		def resp = rest.post(body:[:],requestContentType : "application/json")
		return JSONObject.fromObject(resp.data.text)
	}
	/*
	 * ------------------微信端pc授权登陆方法结束------
	 */	
}
 